package com.mall.seckill.service.impl;

import com.mall.common.response.CommonResponse;
import com.mall.constant.enums.CommonStatus;
import com.mall.constant.strings.SuccessMsg;
import com.mall.entity.TbSeckillItem;
import com.mall.entity.bargain.BgOrder;
import com.mall.seckill.mapper.SeckillOrderMapper;
import com.mall.seckill.service.SeckillOrderService;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 秒杀订单服务impl
 *
 * @author ASUS
 * @date 2021/07/18
 */
@Service
public class SeckillOrderServiceImpl implements SeckillOrderService {

    @Autowired
    private SeckillOrderMapper seckillOrderMapper;

    @Autowired
    private SeckillItemServiceImpl seckillItemService;

    @Autowired
    private Redisson redisson;

    @Override
    public void insert(BgOrder bgOrder) {
        seckillOrderMapper.insert(bgOrder);
    }

    @Override
    public CommonResponse updateOrderStatus(Long id, String status) {
        BgOrder bgOrder = new BgOrder();
        bgOrder.setId(id);
        bgOrder.setStatus(status);
        bgOrder.setUpdateTime(new Date());
        seckillOrderMapper.updateStatusById(bgOrder);
        BgOrder bgOrderById = seckillOrderMapper.findOne(id);
        TbSeckillItem byId = seckillItemService.findById(bgOrderById.getOrderItemId());
        byId.setSaleNum(byId.getSaleNum()+1);
        if (byId.getSeckillNum().equals(byId.getSaleNum())){
            byId.setStatus("3");
        }
        seckillItemService.update(byId);
        seckillItemService.addSeckillToRedis();
        return new CommonResponse(CommonStatus.VALID.getCode(), SuccessMsg.SUCCESS_CODE_200);
    }

    @Override
    public BgOrder findOne(Long id) {
        return seckillOrderMapper.findOne(id);
    }

    /**
     * 定时器
     * 每隔五分钟扫描一次未支付的订单，修改订单状态
     */
    @Scheduled(cron = "0 */5 * * * ?")
    public void findOrderStatus(){
        //定时获取订单信息，过期未支付的改变状态
        long currentTimeMillis = System.currentTimeMillis();
        List<BgOrder> collect = seckillOrderMapper.findAll().stream().filter(item -> {
            return (currentTimeMillis-item.getCreateTime().getTime())/1000/60 > 30 && "0".equals(item.getStatus());
        }).collect(Collectors.toList());
        collect.stream().forEach(item->{
            item.setStatus("3");
            seckillOrderMapper.updateStatusById(item);
        });
    }




}
